﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.IO;
using Microsoft.BusinessData.Infrastructure;
using Microsoft.BusinessData.Runtime;
using Microsoft.BusinessData.MetadataModel;
using Microsoft.BusinessData.MetadataModel.Collections;

using Microsoft.SharePoint;
using MsExchangeBcsConnector.ExchangeBdcModel.Helpers;

using Microsoft.SharePoint.BusinessData.SharedService;
using Microsoft.SharePoint.BusinessData.MetadataModel;

namespace MsExchangeBcsConnector
{
    public class EmlFormatHttpHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            //Connect to BCS
            BdcServiceApplicationProxy proxy =
            (BdcServiceApplicationProxy)SPServiceContext.Current.GetDefaultProxy(
            typeof(BdcServiceApplicationProxy));
            DatabaseBackedMetadataCatalog catalog = proxy.GetDatabaseBackedMetadataCatalog();
            
           /* string LobSystemName = Path.GetDirectoryName(context.Request.Path);
            if (string.IsNullOrEmpty(LobSystemName))
            {
                LobSystemName = Constants.LobSystemName;
            }
            else
            {
                LobSystemName = LobSystemName.Substring(1,);
            }*/

            string MessageId = Base32Url.FromBase32String(System.IO.Path.GetFileNameWithoutExtension(context.Request.Path)); 

            IEntity ect = catalog.GetEntity(Constants.BcsNamespace, Constants.MessageEntityName);
            ILobSystem lob = ect.GetLobSystem();
            ILobSystemInstance lobi = lob.GetLobSystemInstances()[HandlerConstants.LobSystemName];

            string CharacterSet = String.Empty;
            string Name = String.Empty;
            byte[] mc = ExchangeHelper.LoadMessageMimeContent(lobi, MessageId, out CharacterSet, out Name);
            Encoding enc = Encoding.GetEncoding(CharacterSet);
           
            //Download
            context.Response.Clear();
           context.Response.ClearHeaders();

           string FileName = CleanUpFileName(Name);

           context.Response.ContentType = String.Format("application/octet-stream; name={0}", FileName);

            context.Response.AddHeader("content-transfer-encoding", "binary");

            context.Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", FileName));

            context.Response.ContentEncoding = System.Text.Encoding.GetEncoding(CharacterSet);

            context.Response.BinaryWrite(mc);

            context.Response.Flush();

            context.Response.End();
        }

        private const string  Pattern = "/" + HandlerConstants.LobSystemName + "/";

       
        private static string CleanUpFileName(String Name)
        {            
            try
            {
                return Regex.Replace(Name, "[^a-zA-Z-0-9]", "").Trim() + ".eml";
            }
            catch
            {
                return "Message.eml";
            }
        }
    }
}
